package com.zhongxi.guoyuan.OffLineShop;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.utils.ViewUtils;
import com.zhongxi.guoyuan.widget.view.LoadPager;

import io.reactivex.disposables.Disposable;

/**
 * Created by Administrator on 2018/1/9.
 */

public abstract class SuperFragment extends Fragment {

    protected Disposable mDisposable;
    private LoadPager mFrameLayout;
    private ProgressDialog mProgressDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mFrameLayout == null) {
            mFrameLayout = new LoadPager(UiUtils.getContext()) {
                @Override
                public int load() {
                    return SuperFragment.this.load();
                }

                @Override
                protected View getSuccessView() {
                    return SuperFragment.this.getSuccessView();
                }
            };

        }
        return mFrameLayout;
    }

    /**
     * 请求数据
     */
    public void show() {
        if (mFrameLayout != null) {
            mFrameLayout.show();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //viewpager 预加载不到时,就会调用,解决mFrameLayout可能两个父view的问题
        ViewUtils.removeFromParent(mFrameLayout);
        unsubscribe();
    }

    protected void unsubscribe() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    /**
     * 请求服务器数据,返回对应的状态<br>
     * {@link LoadPager#STATUS_ERROR 加载失败} <br>
     * {@link LoadPager#STATUS_EMPTY 加载为空} <br>
     * {@link LoadPager#STATUS_SUCCESS 加载成功} <br>
     *
     * @return
     */
    public abstract int load();

    /**
     * 创建成功<br>
     * 只有{@link #load()} 的返回值是{@link LoadPager#STATUS_SUCCESS}时,才会执行
     *
     * @return
     */
    public abstract View getSuccessView();


    protected void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity(), R.style.CustomProgressDialog);
        }
        mProgressDialog.setMessage("加载中....");
        mProgressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.progressbarstyle_large));
        mProgressDialog.show();
    }

    protected void dismessProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

}
